package com.library.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.library.rest.okhttp.LoggingInterceptor;
import com.library.rest.okhttp.OkHttpHeaderInterceptro;
import com.library.rest.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 在此写用途
 *
 * @version V1.0 <描述当前版本功能>
 * @author: zhiwei
 * @date: 2016-04-16 16:15
 */
public class ApiServiceManager {
    private static boolean DEBUG = false;
    public static String deviceNo;
    public static String tokenId = "";
    public static String token = "";

    public static Retrofit retrofit;
    public static Map<Class, Object> mApiService = new HashMap<>();

    private static OkHttpClient mOkHttpClient;

    public static OkHttpClient getmOkHttpClient() {
        return mOkHttpClient;
    }

    public static void setDebug(boolean debug) {
        DEBUG = debug;
    }

    public static void clearToken() {
        tokenId = "";
        token = "";
    }

    public static void init(String url, Interceptor... interceptors) {
        OkHttpClient.Builder builder = RetrofitUrlManager.getInstance().
            //RetrofitUrlManager 初始化
            with(new OkHttpClient.Builder())
            .readTimeout(5, TimeUnit.SECONDS)
            .connectTimeout(5, TimeUnit.SECONDS);

        if (interceptors != null) {
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
        }

        mOkHttpClient = builder.build();
        retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(mOkHttpClient)
            .build();
    }

    public static void init(String uri) {
        List<Interceptor> lists = new ArrayList<>(2);
        lists.add(new OkHttpHeaderInterceptro());
        if (DEBUG) {
            lists.add(new LoggingInterceptor());
        }
        Interceptor[] in = new Interceptor[1];
        in = lists.toArray(in);

        init(uri, in);
    }

    public static <T> T getOrCreateApiService(Class<T> apiService) {
        if (retrofit == null) {
            throw new RuntimeException("you mast init by ApiServiceManager.init()");
        }
        if (mApiService.containsKey(apiService)) {
            return (T)mApiService.get(apiService);
        }
        T api = retrofit.create(apiService);
        mApiService.put(apiService, api);
        return api;
    }

    //private static final class OkHttpHeaderInterceptro implements Interceptor {
    //    private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    //    Random mRandom = new Random();
    //    private static final String KEY_A = "TKIHDEKD6FOKKKMTFd68";
    //    private static final String KEY_B = "QCTD458JDYKTKIHDECTD";
    //
    //    @Override
    //    public Response intercept(Chain chain) throws IOException {
    //        Request.Builder rBuild = chain.request().newBuilder();
    //        Date nowDate = new Date();
    //        String time = dateTimeFormat.format(nowDate);
    //        //            String sn = String.valueOf(mRandom.nextInt(100000));
    //        String body = stringifyRequestBody(chain.request());
    //        StringBuffer buffer = new StringBuffer();
    //        buffer.append(body);
    //        String deviceId = deviceNo;
    //        //            if (BuildConfig.DEBUG) {
    //        //                deviceId = "111";
    //        //            }
    //        rBuild.addHeader("time", time)
    //            //                .addHeader("sn", sn)
    //            //小写 MD5:固定部 A+time+sn+data 部+ 固定部 B
    //            //                .addHeader("sign", MD5.string2MD5(buffer.toString()))
    //            //                .addHeader("ver", "android1.0")
    //            //                .header("Content-Type", "*/*")
    //            .header("deviceId", deviceId)
    //            .header("Encoding", "UTF-8")
    //            .header("tokenId", tokenId == null ? "" : tokenId)
    //            .header("token", token == null ? "" : token);
    //
    //        return chain.proceed(rBuild.build());
    //    }
    //
    //    private static String stringifyRequestBody(Request request) {
    //        try {
    //            final Request copy = request.newBuilder().build();
    //            if (copy != null) {
    //                final Buffer buffer = new Buffer();
    //                RequestBody requestBody = copy.body();
    //                if (requestBody != null) {
    //                    requestBody.writeTo(buffer);
    //                    return buffer.readUtf8();
    //                }
    //            }
    //
    //        } catch (final IOException e) {
    //            return "did not work";
    //        }
    //        return "";
    //    }
    //}
}
